package com.jidolstar.astro
{
	/**
	 * 시간 단위를 가지는 값을 담는 클래스
	 * @author Yongho,Ji (jidolstar@gmail.com)
	 * @since 2009.03.31 
	 */ 	
	public class ALHMS {
		private var isSetFractionalHour:Boolean;
		private var isSetHMS:Boolean;
		private var _fractionalHour:Number;
		private var _hour:int;
		private var _minute:int;
		private var _second:Number;
		public function ALHMS( $hour:int = 0, $minute:int = 0, $second:Number = 0 ):void {
			isSetFractionalHour = false;
			isSetHMS = true;
			_hour = $hour;
			_minute = $minute;
			_second = $second;
		}
		public function setHMS( $hour:int, $minute:int, $second:Number ):void {
			isSetFractionalHour = false;
			isSetHMS = true;
			_hour = $hour;
			_minute = $minute;
			_second = $second;			
		}
		public function get hour():int {
			if( !isSetHMS ) fractionalHour2HMS();
			return _hour;
		}
		public function get minute():int {
			if( !isSetHMS ) fractionalHour2HMS();
			return _minute;
		}
		public function get second():Number {
			if( !isSetHMS ) fractionalHour2HMS();
			return _second;
		}
		public function get fractionalHour():Number {
			if( !isSetFractionalHour ) {
				isSetFractionalHour = true;
				_fractionalHour = _hour + _minute/60.0 + _second/3600.0;
			}
			return _fractionalHour;
		}
		public function set fractionalHour( $value:Number ):void {
			if( isNaN( $value ) ) {
				throw new ArgumentError( "value is NaN" );
			} 
			isSetFractionalHour = true;
			isSetHMS = false;
			_fractionalHour = $value;
		}
		public function toString( $h:String = "h", $m:String = "m", $s:String = "s", $secondToFixed:uint = 2 ):String {
			var hour:String = _hour < 10 ? "0"+_hour : _hour.toString();
			var minute:String = _minute < 10 ? "0" + _minute : _minute.toString();
			var second:String = _second < 10 ? "0" + _second.toFixed( 20 ) : _second.toFixed( 20 );
			var seconds:Array = second.split(".");
			if( $secondToFixed > 0 ) {
				second = seconds[0] + "." + String(seconds[1]).substr( 0, $secondToFixed ) + $s;
			} else {
				second = seconds[0] + $s;
			}			
			return hour + $h + minute + $m + second ;			
		} 
		private function fractionalHour2HMS():void {
			var temp:Number;
			_hour = Math.floor( _fractionalHour );
			temp = _fractionalHour - _hour;
			temp *= 60.0;
			_minute = Math.floor( temp );
			temp -= _minute;
			temp *= 60.0;
			_second = temp;			
		}		
		static public function HMS2FractionalHour( $hour:int, $minute:int, $second:Number ):Number {
			return $hour + $minute/60.0 + $second/3600.0;
		}
		static public function fractionalHour2HMS( $fractionalHour:Number ):ALHMS {
			var temp:Number;
			var hour:int = Math.floor( $fractionalHour );
			temp = $fractionalHour - hour;
			temp *= 60.0;
			var minute:int = Math.floor( temp );
			temp -= minute;
			temp *= 60.0;
			var second:Number = temp;
			return new ALHMS( hour, minute, second );				
		}		
	}
}